<template>
  <el-container>
    <el-header>
      <el-form :inline="true" :model="searchObj" class="demo-form-inline">
        <el-form-item label="">
          <el-select v-model="searchObj.field" placeholder="检索字段" clearable>
            <el-option label="标题" value="title" selected></el-option>
            <el-option label="内容" value="content"></el-option>
            <el-option label="关键词" value="keywords"></el-option>
            <el-option label="摘要" value="digest"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-autocomplete
              v-model="searchObj.keyword"
              placeholder="请输入检索关键字"
              :fetch-suggestions="querySearchAsync"
              style="width: 400px"
              @select="handleSelect"
              @keydown.enter.native="onSubmit" clearable>
          </el-autocomplete>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="success" @click="dialogVisible = true">高级查询</el-button>
        </el-form-item>
      </el-form>

      <el-dialog
          title="高级查询"
          :visible.sync="dialogVisible"
          width="80%"
          :before-close="handleClose">

          <el-form :model="formData" ref="formData" label-width="80px" class="form-dynamic">
            <el-form-item
                v-for="(domain, index) in formData.domains"
                :label="'查询条件' + (index+1)" label-width="15%"
                :key="domain.key"
                :prop="'domains.' + index + '.value'"
                :rules="{required: true, message: '内容不能为空', trigger: 'blur'}">
              <el-input v-model="domain.value" style="width: 80%"></el-input>&nbsp;
              <a class="remove-item" v-show="formData.domains.length>1" @click.prevent="removeDomain(domain)"><i class="el-icon-close"></i></a>
            </el-form-item>
            <el-form-item class="submit-btn">
              <el-button type="primary" @click="submitForm('formData')">提交</el-button>
              <el-button @click="addDomain">新增一项</el-button>
              <el-button @click="resetForm('formData')">重置</el-button>
            </el-form-item>
          </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </el-header>
    <el-container>
      <el-aside>
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix" style="margin: 10%">
            <span style="font-weight: bolder">搜索推荐 </span><i class="el-icon-mouse"></i>
            <!--<el-button style="float: right; padding: 3px 0" type="text">更多</el-button>-->
          </div>

          <div class="text item"  v-for="(relative,index) in relatives">
            <a href="#"><el-tag :type="tagType[index%4]" effect="dark" @click="searchRelation(relative.value)" >{{ relative.value }}</el-tag></a>
          </div>


        </el-card>
      </el-aside>
      <el-main class="back">
        <div>
          <el-radio-group v-model="show" size="medium">
            <el-radio-button v-for="(item,index) in types" :label="index">{{ item }}</el-radio-button>

          </el-radio-group>
        </div>
        <br>
                <el-table
                    :data="items"
                    stripe
                    tooltip-effect="light"
                    style="width: 100%">
                  <el-table-column
                      width="400%"
                      prop="title"
                      align="center"
                      label="标题"
                      :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                      <p v-html='scope.row.title' class="table_class"></p>
                    </template>
                  </el-table-column>

                  <el-table-column
                      width="300%"
                      prop="keywords"
                      align="center"
                      label="关键字"
                      :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                      <p v-html='scope.row.keywords' class="table_class"></p>
                    </template>
                  </el-table-column>
                  <el-table-column
                      prop="time"
                      align="center"
                      label="上传日期"
                      :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                      <p v-html='scope.row.time' class="table_class"></p>
                    </template>
                  </el-table-column>
                  <el-table-column
                      prop="author"
                      align="center"
                      label="部门/作者"
                      :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                      <p v-html='scope.row.author' class="table_class"></p>
                    </template>
                  </el-table-column>
                  <el-table-column
                      label="操作"
                      align="center">
                    <template slot-scope="scope">
                      <el-button type="success" size="small" icon="el-icon-edit" @click="toInfo(scope.row.id)" round>查看</el-button>
                    </template>
                  </el-table-column>
                </el-table>

        <br>

        <!--百度格式数据展示-->
        <!--<div class="listItem" v-for="item in show_items">
          <a href="#" v-html="item.title" class="title" @click="onCheck"></a>
          <span class="author">{{ item.author }} {{ item.time }}</span>
          <span v-html="item.keywords" class="keywords"></span>
          <span v-html="item.createAbstract" class="digest"></span>
        </div>-->

        <div class="block">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5, 10, 15]"
              :page-size="searchObj.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="sum">
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>
<script>
export default {
  name: 'Search',
  //通过计算，实现不同类别的切换
  computed: {
    show_items: function () {
      console.log(this.show)
      if (this.show != 0) {
        console.log(this.show)
        let ret = [];
        for (let i = 0; i < this.items.length; ++i) {
          if (i % 3 == this.show)
            ret.push(this.items[i]);
        }
        return ret;
      }
      return this.items;
    }
  },
  data() {
    return {
      input: '',
      // 搜索条件构造
      searchObj: {
        field: 'title',
        keyword: '',
        from: 0,
        size: 5
      },
      // 相关推荐
      relatives: [],
      tagType: [" ","info","success","danger"],
      // 返回列表
      items: [],
      sum: 0,
      currentPage: 1,
      // 分类
      show: 0,
      types: ["产品设计","科研项目","质量维保","知网文献","构型","仿真","试验","规划指南","标准规范","经验方法","情报文献","专题资料"],
      // 搜索推荐
      suggestions: [],
      suggestionsByKeyword: [],
      timeout: null,
      // 高级查询
      dialogVisible: false,
      formData: {
        domains: [{
          value: ''
        }],
      }

    }
  },
  created() {
    this.selectAll();
  },
  mounted() {
    this.suggestTop()
  },
  methods: {
    selectAll() {
      const _this = this
      axios.get('search/all', {
        params: this.searchObj
      }).then(function (resp) {
        //用于分页
        _this.items = resp.data.data.list
        _this.sum = resp.data.data.sum
      })
      this.suggestTop()
    },
    // 搜索
    onSubmit() {
      const _this = this
      if (this.searchObj.keyword == '' || this.searchObj.field == '') {
        /*this.$message({
          message: '查询条件为空，请检查',
          type: 'warning',
          center: true
        });*/
        this.selectAll()
      } else {
        axios.get('search/matchQuery', {
          params: this.searchObj
        }).then(function (resp) {
          _this.items = resp.data.data.list
          _this.sum = resp.data.data.sum
        })
        // 更新搜索推荐
        this.updateSuggest()
        // 更新侧边栏推荐
        this.freshSearchRelation()
      }
    },
    // 更新搜索推荐
    updateSuggest(){
      axios.get('search/suggestion/update/' + this.searchObj.keyword).then(function (resp) {
        // 返回成功 console.log(resp.data.data)
      })
    },
    // 刷新侧边栏推荐信息
    freshSearchRelation(){
      const _this = this
      axios.get('search/searchRelation/' + this.searchObj.keyword).then(function (resp) {
        _this.relatives = resp.data.data.list
      })
    },
    /*侧边栏搜索推荐*/
    searchRelation(relation){
      this.searchObj.keyword = relation
      this.onSubmit()
    },

    // 高级查询的弹框
    handleClose(done) {
      this.$confirm('是否要放弃高级查询？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    },
    /*增加表单项*/
    addDomain() {
      this.formData.domains.push({
        value: '',
      });
    },
    /*删除表单项*/
    removeDomain(item) {
      var index = this.formData.domains.indexOf(item)
      if (index !== -1) {
        this.formData.domains.splice(index, 1)
      }
    },
    /*格式化表单数据*/
    formatData(data){   //动态表单生成的是一个对象数组，需要把对象数组转成一个对象
      let obj = {};
      data.forEach((item,index)=>{
        obj['value'+(index+1)] = item.value
      });
      return obj
    },
    /*提交表单*/
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          console.log(this.formatData(this.formData.domains))
        } else {
          alert('表单项不能为空！！！');
          return false;
        }
      });
    },
    /*重置表单*/
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },


  // 处理分页
    handleSizeChange(val) {
      this.searchObj.size = val
      this.onSubmit()
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.searchObj.from = (val - 1) * this.searchObj.size
      this.onSubmit()
      // console.log(`当前页: ${val}`);
    },
    onCheck() {
      this.$router.push(
          {
            path: `/pdf`
          }
      )
    },
    toInfo(id) {
      this.$router.push(
          {
            path: '/info',
            query: {
              id: id,
              keyword: this.searchObj.keyword
            }
          }
      )
    },
    // 搜索推荐前十
    suggestTop() {
      const _this = this
      axios.get('search/suggestion/top').then(function (resp) {
        _this.suggestions = resp.data.data.list
        _this.relatives = resp.data.data.list
      })
    },
    suggestByKeyword(queryString) {
      const _this = this
      return axios.get('search/suggestion/' + queryString).then(function (resp) {
        _this.suggestionsByKeyword = resp.data.data.list
      })
    },
    async querySearchAsync(queryString, cb) {
      if (queryString != '') await this.suggestByKeyword(queryString)
      var suggestions = this.suggestions
      var suggestionsByKeyword = this.suggestionsByKeyword
      var results = queryString ? suggestionsByKeyword : suggestions;
      // console.log(results)
      // clearTimeout(this.timeout);
      // this.timeout = setTimeout(() => {
      //   cb(results);
      // }, 3000 * Math.random());
      cb(results)
    },
    handleSelect(item) {
      console.log(item.value);
    }

  }
}
</script>
<style>

.listItem {
  width: 100%;
  border-radius: 5px;
  margin-bottom: 10px;
  padding: 10px;
}

.listItem:hover {
  /*-webkit-box-shadow:0px 3px 3px #c8c8c8 ;*/
  /*-moz-box-shadow:0px 3px 3px #c8c8c8 ;*/
  /*box-shadow:0px 3px 3px #c8c8c8;*/
  /*background-color: antiquewhite;*/
  border-left: red 2px solid;
  margin-left: -2px
}

.title {
  font-weight: bold;
  width: 100%;
  display: inline-block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.keywords {
  display: block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.author {
  display: block;
  font-weight: lighter;
  font-size: smaller;
}

.digest {
  font-weight: lighter;
  font-size: smaller;
  color: #409EFF;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  display: -moz-box;
  -moz-line-clamp: 2;
  -moz-box-orient: vertical;
  word-wrap: break-word;
  word-break: break-all;
  white-space: normal;
}

.back {
  border-radius: 10px;
  text-align: left;
}

.table_class {
  text-align: left;
}

/*相关推荐*/
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 90%;
}
</style>
